class VideosController < WebappController
  before_filter :ensure_authenticated, :except=>[:index, :show]
  
  def index
    user_id = params[:user_id]
    @user = User.find(user_id) if user_id
    
    @videos = Video.paginate(:order=>"created_at DESC",:page => params[:page], :per_page=>WebappConstants::RECORDS_PER_PAGE) unless @user
    @videos = Video.paginate(:order=>"created_at DESC",:conditions=>["user_id=?", user_id], :page => params[:page], :per_page=>WebappConstants::RECORDS_PER_PAGE) if @user
    @videos
    
  end
  
  def show
    @video = Video.find(params[:id])
    #used for commenting the video
    #@comment = Comment.new  
  end
  
  def new
    @video = Video.new
  end
  
  def comment
    @video = Video.find(params[:id])
    comment = Comment.new(params[:comment])
    comment.user_id = user_session.user_id
    @video.comments << comment
    respond_to do |format|
      format.html { redirect_to user_video_path(@video) }
      format.fbml { redirect_to user_video_path(@video) }
      format.json { render :json => json_rtn.to_json }
      format.fbjs { render :partial=>"comments/comment", :object=> comment}
      
    end
    
    
  end
  
  def discover_video_info
    url = params[:url]
    rtn = {:error=>"Could not get the content from the URL"}
    #check if has url
    if url
      video_service = VideoUtils::VideoUtils.find_video_service(url)
      
      #check is the video service is supported
      if video_service == VideoUtils::UNKNOWN
        rtn = {:error=>t(:video_service_not_supported)}
      else
        video_id = VideoUtils::VideoUtils.find_video_id(url,video_service)
        #check if the video already exists
        if Video.find_by_video_id(video_id)
          rtn = {:error=>t(:video_already_submited)}
        else
          
          extracter = VideoUtils::VideoInfoExtracter.new(url)
          if extracter.processed?
            #check if the video exists for any user
            fbml_video_code = "<fb:swf swfbgcolor='000000' imgstyle='border-width:3px; border-color:white;' swfsrc='http://www.youtube.com/v/#{video_id}' width='200' height='144'/>"
            rtn = {:fbml_video_code=>fbml_video_code,:video_id=>video_id, :video_service=>video_service,:description=>extracter.description,:title=>extracter.title}    
          end
        end
      end
      
      
    end
    respond_to do |format|
      #  success = "Thanks for your vote!"
      #  format.html { flash[:success] = success; redirect_to_last_page }
      #  format.fbml { flash[:success] = success; redirect_to_last_page }
      format.json { render :json => rtn.to_json }
      format.fbjs { render :json => rtn.to_json }
      #  format.fbjs { render :json => {:msg => "success"}.to_json }
    end
  end
  
  def vote
    @video = Video.find(params[:id])
    #cannot vote in own video 
    #check if has voted already
    #votes = @video.find_votes_cast_by_user(user_session.user_id)
    json_rtn = nil
    flashing = nil;
    if @video.voted_by_user_id?(user_session.user_id)
      flashing = lambda {flash_error(:you_already_voted)}
      json_rtn = {:error=>t(:you_already_voted)}
    elsif @video.user_id != user_session.user_id 
      @video.votes << Vote.new(:vote=>true, :user_id=>user_session.user_id)
      flashing = lambda {flash_notice(:thank_you_for_voting)}
    else
      flashing = lambda{flash_error(:cannot_vote_in_own_video)}  
      json_rtn = {:error=>t(:cannot_vote_in_own_video)}
    end
    
    unless json_rtn
      html_to_update = "(#{sprintf(I18n.t(:votes_info),@video.votes.count)} )" if @video.votes.count == 1
      html_to_update = "(#{sprintf(I18n.t(:votes_info).pluralize,@video.votes.count)} )" if @video.votes.count > 1
      html_to_update = "" if @video.votes.count == 0
      json_rtn = {:video_id=>@video.id, :votes_count=>@video.votes.count, :html_to_update=>html_to_update, :message=>t(:thank_you_for_voting)}
    end
    respond_to do |format|
      format.html { flashing.call; render :action=>:show }
      format.fbml { flashing.call; render :action=>:show }
      format.json { render :json => json_rtn.to_json }
      format.fbjs { render :json => json_rtn.to_json }
    end
    #flashing.call
    #render :action=>:show
    
  end
  def create
    @video = Video.new(params[:video])
    raise Webapp::BadParametersError unless params[:user_id]
    raise Webapp::WrongAuthenticatedUser if params[:user_id].to_i!= user_session.user_id
    @video.user_id = params[:user_id]
    #Find the video service. Now only supports youtube
    #service = Video::VideoUtils.find_video_service( @video.url)
    
    #raise Webapp::VideoServiceNotSupported unless service == Video::YOUTUBE
    
    #if the video is a youtube video, then get the id
    
    #@video.youtube_video_id = Video::VideoUtils.find_video_id(@video.url,service)
    
    #raise Webapp::VideoUnrecognized unless @video.youtube_video_id
    if !@video.save
      #flash_notice(:video_submited, "#{WebappConstants::SUBMISSION_POINTS[WebappConstants::VIDEO_RESOURCE]}")
      #else 
      render :action => "new"
    end    
    #rescue Webapp::VideoServiceNotSupported
    #flash_error(:video_service_not_supported)
    #  @video.errors.add(:url, t(:video_service_not_supported))
    #  render :action => "new"
    
    #rescue Webapp::VideoUnrecognized
    #flash_error(:video_not_recognized)
    #   @video.errors.add(:url, t(:video_not_recognized))
    #  render :action => "new"
  end
  
  def destroy
    @video = Video.find(params[:id])
    raise Webapp::BadParametersError unless params[:user_id]
    raise Webapp::WrongAuthenticatedUser if params[:user_id].to_i!= user_session.user_id and !User.find(user_session.user_id).admin
    @video.destroy
    #loging out
    flash_notice(:video_removed)
    respond_to do |format|
      format.html { redirect_to(user_videos_path) }
      format.fbml { redirect_to(user_videos_path) }
      format.xml  { head :ok }
    end
  end
  
end
